// Create Folders Controller
// creates the folder if it doesn't exists

function getOrCreateFolder(folderPath) {
    if (folderPath == "") {
        return null;
    }
    var folder = roothome.childByNamePath(folderPath);
    if (folder === null) {
        var pathComponents = folderPath.split('/');
        var base = pathComponents.slice(0, -1);
        var rest = pathComponents.slice(-1);
        parentFolder = getOrCreateFolder(base.join('/')); 
	    return parentFolder.createFolder(rest.join('/'));
    }
    return folder; 
}

function createFolders(folderName) {

    if (!folderName) {
       status.code = 400;
       return {success: false, message: "Folder not specified"};
    }

    try {
        var folder = getOrCreateFolder(folderName);
    } catch (err) {
        status.code = 500; 
        return {success: false, 
                message: "Error creating folder: " + err};
    }

    if (folder === null || !folder.isContainer) {
       status.code = 500;
       return {success: false, 
               message: "Folder " + folderName + " could not be created"};
    }

    return {success: true, 
            message: "Folder " + folderName + " was created successfully"}

}

var result = createFolders(args.folder);
model.message = jsonUtils.toJSONString(result);

